<template>
  <div>
    <a-transfer
      :data-source="mockData"
      :target-keys="targetKeys"
      :disabled="disabled"
      :show-search="showSearch"
      :filter-option="filterOption"
      :show-select-all="false"
      @change="onChange"
      @search="onSearch"
    >
      <template
        slot="children"
        slot-scope="{
          props: { direction, filteredItems, selectedKeys, disabled: listDisabled },
          on: { itemSelectAll, itemSelect },
        }"
      >
        <a-table
          :row-selection="getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })"
          :rowKey="keyName"
          :columns="tabColumns"
          :data-source="filteredItems"
          size="small"
          :style="{ pointerEvents: listDisabled ? 'none' : null }"
          :pagination="direction === 'left' ? paginationLeft : paginationRight"
          @change="pageChange"
          :custom-row="
            ({ key, disabled: itemDisabled }) => ({
              on: {
                click: () => {
                  if (itemDisabled || listDisabled) return
                  itemSelect(key, !selectedKeys.includes(key))
                },
              },
            })
          "
        />
      </template>
    </a-transfer>
  </div>
</template>
<script>
import difference from 'lodash/difference'
import { getAction, postAction } from '@/api/manage'
import debounce from 'lodash/debounce'
export default {
  props: {
    url: {
      Type: String,
      default: '',
    },
    keyName: {
      Type: String,
      default: 'id',
    },
    tabColumns: {
      Type: Array,
      default: () => [],
    },
    initOriginTargetKeysUrl: {
      Type: String,
      default: '',
    },
    originTargetKeys: {
      Type: Array,
      default: () => [],
    },
    projectBuildId: {
      Type: String,
      default: '',
    },
    syncParent: {
      Type: Boolean,
      default: false,
    },
    params: {
      Type: Object,
      default: () => {
        return {}
      },
      require: false,
    },
  },
  watch: {},
  data() {
    this.onSearch = debounce(this.onSearch, 500)
    return {
      mockData: [],
      keyword: '',
      targetKeys: this.originTargetKeys,
      targetRows: [],
      disabled: false,
      showSearch: true,
      paginationLeft: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        total: 0,
      },
      paginationRight: {
        defaultCurrent: 1,
        defaultPageSize: 9,
        pageSize: 10,
        total: 0,
      },
    }
  },
  methods: {
    pageChange(page) {
      if (page.defaultPageSize == 10) {
        this.initMockData(page.current)
      }
    },
    filterOption(inputValue, option) {
      var flag = false
      this.tabColumns.forEach((c) => {
        if (option[c.dataIndex].indexOf(inputValue) > -1) {
          return (flag = true)
        }
      })
      return flag
    },
    onChange(nextTargetKeys) {
      this.targetKeys = nextTargetKeys
      this.targetRows = []
      this.mockData.forEach((item) => {
        if (this.targetKeys != null && this.targetKeys.length > 0 && this.targetKeys.indexOf(item.key) > -1) {
          this.targetRows.push(item)
        }
      })
      if (this.syncParent) {
        this.$emit('targetRows', JSON.stringify(this.targetRows))
      }
      this.paginationLeft.current = 1
      this.initMockData(1)
    },
    onSearch(direction, value) {
      if (direction == 'left') {
        this.keyword = value
        this.initMockData(1)
      }
    },
    getRowSelection({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
      return {
        getCheckboxProps: (item) => ({ props: { disabled: disabled || item.disabled } }),
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows.filter((item) => !item.disabled).map(({ key }) => key)
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys)
          itemSelectAll(diffKeys, selected)
        },
        onSelect({ key }, selected) {
          itemSelect(key, selected)
        },
        selectedRowKeys: selectedKeys,
      }
    },
    initMockData(curr) {
      var vm = this
      vm.mockData = []
      if (vm.targetRows != null && vm.targetRows.length > 0) {
        vm.mockData = JSON.parse(JSON.stringify(vm.targetRows))
      } else if (this.targetKeys != null && this.targetKeys.length > 0 && this.targetKeys[0]) {
        let paramsInner = {}
        paramsInner = Object.assign(paramsInner, this.params, { contaionKeys: this.targetKeys.join(',') })
        getAction(this.url, paramsInner)
          .then((res) => {
            if (res.code == 0 || res.code == 200 || res.success) {
              if (res.result != null && res.result.records != null) {
                res.result.records.forEach((record) => {
                  record.key = record[vm.keyName]
                  vm.mockData.push(record)
                  this.targetRows.push(record)
                })
              }
            }
          })
          .catch((res) => {
            vm.$message.warning('初始化穿梭框选项出错:' + (res.message || res.msg))
          })
      }
      let params = {}
      params = Object.assign(params, this.params, {
        keyword: this.keyword,
        pageNo: curr,
        pageSize: 10,
        targetKeys: this.targetKeys.join(','),
        projectBuildId: this.projectBuildId,
      })
      getAction(this.url, params)
        .then((res) => {
          if (res.code == 0 || res.code == 200 || res.success) {
            if (res.result != null && res.result.records != null) {
              vm.paginationLeft.total = res.result.total
              res.result.records.forEach((record) => {
                record.key = record[vm.keyName]
                vm.mockData.push(record)
              })
              vm.paginationLeft.defaultCurrent = curr
              vm.paginationLeft.current = curr
            } else if (res.result != null && res.result != null && this.projectBuildId != '') {
              vm.paginationLeft.total = res.result.length
              res.result.forEach((record) => {
                record.key = record[vm.keyName]
                vm.mockData.push(record)
              })
              vm.paginationLeft.defaultCurrent = curr
              vm.paginationLeft.current = curr
            } else {
              vm.paginationLeft.total = 0
              vm.$message.warning('加载穿梭框选项为空')
            }
          } else {
            vm.$message.warning('加载穿梭框选项异常:' + (res.message || res.msg))
          }
        })
        .catch((res) => {
          vm.$message.warning('加载穿梭框选项出错:' + (res.message || res.msg))
        })
    },
    initOriginTargetKeys() {
    console.log('tran')
    console.log(this.originTargetKeys)
      if (!this.initOriginTargetKeysUrl || this.originTargetKeys == null || this.originTargetKeys.length < 1) {
        this.initMockData(1)
        //搜索框聚焦
        $('.ant-transfer-list-search')[0].focus()
        return
      }
      var vm = this
      getAction(this.initOriginTargetKeysUrl, { ids: this.originTargetKeys.join(',') })
        .then((res) => {
          if (res.code == 0 || res.code == 200 || res.success) {
            if (res.result != null) {
              res.result.forEach((record) => {
                record.key = record[vm.keyName]
                vm.targetRows.push(record)
                vm.targetKeys.push(record.key)
              })
            }
          } else {
            vm.$message.warning('初始化穿梭框已选选项异常:' + (res.message || res.msg))
          }
          vm.initMockData(1)
        })
        .catch((res) => {
          vm.$message.warning('初始化穿梭框已选选项出错:' + (res.message || res.msg))
        })

      //搜索框聚焦
      $('.ant-transfer-list-search')[0].focus()
    },
  },
  mounted() {
    console.log('mounted')
    console.log(this.originTargetKeys)
    this.initOriginTargetKeys()
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-transfer-list-header {
  display: none;
}
/deep/ .ant-transfer-list {
  padding: 10px;
  height: 550px;
  overflow: scroll;
}
/deep/ .ant-btn-primary {
  color: #1890ff;
}
/deep/ .ant-transfer-operation .ant-btn-primary {
  background-color: #f5f5f5 !important;
}
</style>